const mysql = require('mysql2/promise');

async function main() {
    const args = process.argv.slice(2);
    let id = 0;
    let level = 1;
    let exp = 100;
    for (let i = 0; i < args.length; i++) {
        if (args[i] === '--id' && args[i + 1]) id = parseInt(args[i + 1], 10);
        if (args[i] === '--level' && args[i + 1]) level = parseInt(args[i + 1], 10);
        if (args[i] === '--exp' && args[i + 1]) exp = parseInt(args[i + 1], 10);
    }
    if (!id) {
        console.error('用法: node scripts/set-character-level.js --id 2001 --level 50 --exp 294032');
        process.exit(1);
    }

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };

    let conn;
    try {
        conn = await mysql.createConnection(db);
        await conn.beginTransaction();

        await conn.execute('UPDATE characters SET lvl = ?, exp = ? WHERE id = ?', [level, exp, id]);

        const [rows] = await conn.execute('SELECT id FROM character_training WHERE character_id = ? LIMIT 1', [id]);
        if (rows && rows.length) {
            await conn.execute(
                'UPDATE character_training SET is_training = 0, training_status = 0, training_hours = 0, pending_exp = 0, training_start_time = NULL, training_end_time = NULL, updated_at = NOW() WHERE character_id = ?',
                [id]
            );
        } else {
            await conn.execute(
                'INSERT INTO character_training (character_id, training_hours, total_training_hours, is_training, training_status, pending_exp, created_at, updated_at) VALUES (?, 0, 0, 0, 0, 0, NOW(), NOW())',
                [id]
            );
        }

        await conn.commit();
        console.log(`已设置角色 ${id} 等级=${level}, exp=${exp}，并重置训练状态`);
    } catch (e) {
        if (conn) await conn.rollback().catch(() => { });
        console.error('设置失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
